<template>
  <view>
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title"></view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
        <button class="uni-button" type="default" size="mini" @click="search">搜索</button>
        <button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
        <button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length" @click="delTable">批量删除</button>
        <download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
          <button class="uni-button" type="primary" size="mini">导出 Excel</button>
        </download-excel>
      </view>
    </view>
    <view class="uni-container">
      <unicloud-db ref="udb" :collection="collectionList" field="user_id,order_type,order_status,pay_status,address_id,order_items,order_tradecodes,shop_groups,total_amount,shipping_fee,discount_amount,final_amount,payment_method,pay_time,ship_time,receive_time,finish_time,cancel_time,cancel_reason,remark,create_time,expire_time,evaluate_status" :where="where" page-data="replace"
        :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
        v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual" @load="onqueryload">
        <uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
          <uni-tr>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'user_id')">用户ID</uni-th>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.order_type_localdata" @filter-change="filterChange($event, 'order_type')">订单类型</uni-th>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.order_status_localdata" @filter-change="filterChange($event, 'order_status')">订单状态</uni-th>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.pay_status_localdata" @filter-change="filterChange($event, 'pay_status')">支付状态</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'address_id')">收货地址ID</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'order_items')">订单商品</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'order_tradecodes')">商品tradecode</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'shop_groups')">店铺分组</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'total_amount')">商品总金额</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'shipping_fee')">运费</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'discount_amount')">优惠金额</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'final_amount')">实付金额</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'payment_method')" sortable @sort-change="sortChange($event, 'payment_method')">支付方式</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'pay_time')" sortable @sort-change="sortChange($event, 'pay_time')">支付时间</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'ship_time')" sortable @sort-change="sortChange($event, 'ship_time')">发货时间</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'receive_time')" sortable @sort-change="sortChange($event, 'receive_time')">收货时间</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'finish_time')" sortable @sort-change="sortChange($event, 'finish_time')">完成时间</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'cancel_time')" sortable @sort-change="sortChange($event, 'cancel_time')">取消时间</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'cancel_reason')" sortable @sort-change="sortChange($event, 'cancel_reason')">取消原因</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'remark')" sortable @sort-change="sortChange($event, 'remark')">订单备注</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'create_time')" sortable @sort-change="sortChange($event, 'create_time')">创建时间</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'expire_time')" sortable @sort-change="sortChange($event, 'expire_time')">过期时间</uni-th>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.evaluate_status_localdata" @filter-change="filterChange($event, 'evaluate_status')">评价状态</uni-th>
            <uni-th align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item,index) in data" :key="index">
            <uni-td align="center">{{item.user_id}}</uni-td>
            <uni-td align="center">{{options.order_type_valuetotext[item.order_type]}}</uni-td>
            <uni-td align="center">{{options.order_status_valuetotext[item.order_status]}}</uni-td>
            <uni-td align="center">{{options.pay_status_valuetotext[item.pay_status]}}</uni-td>
            <uni-td align="center">{{item.address_id}}</uni-td>
            <uni-td align="center">{{item.order_items}}</uni-td>
            <uni-td align="center">{{item.order_tradecodes}}</uni-td>
            <uni-td align="center">{{item.shop_groups}}</uni-td>
            <uni-td align="center">{{item.total_amount}}</uni-td>
            <uni-td align="center">{{item.shipping_fee}}</uni-td>
            <uni-td align="center">{{item.discount_amount}}</uni-td>
            <uni-td align="center">{{item.final_amount}}</uni-td>
            <uni-td align="center">{{item.payment_method}}</uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.pay_time"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.ship_time"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.receive_time"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.finish_time"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.cancel_time"></uni-dateformat>
            </uni-td>
            <uni-td align="center">{{item.cancel_reason}}</uni-td>
            <uni-td align="center">{{item.remark}}</uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.create_time"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.expire_time"></uni-dateformat>
            </uni-td>
            <uni-td align="center">{{options.evaluate_status_valuetotext[item.evaluate_status]}}</uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini" type="primary">修改</button>
                <button @click="confirmDelete(item._id)" class="uni-button" size="mini" type="warn">删除</button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<script>
  import { enumConverter, filterToWhere } from '../../js_sdk/validator/intangible_userorders.js';

  const db = uniCloud.database()
  // 表查询配置
  const dbOrderBy = '' // 排序字段
  const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
  // 分页配置
  const pageSize = 20
  const pageCurrent = 1

  const orderByMapping = {
    "ascending": "asc",
    "descending": "desc"
  }

  export default {
    data() {
      return {
        collectionList: "intangible_userorders",
        query: '',
        where: '',
        orderby: dbOrderBy,
        orderByFieldName: "",
        selectedIndexs: [],
        options: {
          pageSize,
          pageCurrent,
          filterData: {
            "order_type_localdata": [
              {
                "text": "全新商品",
                "value": 0
              },
              {
                "text": "转售商品",
                "value": 1
              },
              {
                "text": "混合订单",
                "value": 2
              }
            ],
            "order_status_localdata": [
              {
                "text": "待付款",
                "value": 0
              },
              {
                "text": "待发货",
                "value": 1
              },
              {
                "text": "待收货",
                "value": 2
              },
              {
                "text": "待评价",
                "value": 3
              },
              {
                "text": "已完成",
                "value": 4
              },
              {
                "text": "已取消",
                "value": 5
              },
              {
                "text": "退款中",
                "value": 6
              },
              {
                "text": "已退款",
                "value": 7
              }
            ],
            "pay_status_localdata": [
              {
                "text": "未支付",
                "value": 0
              },
              {
                "text": "已支付",
                "value": 1
              },
              {
                "text": "部分退款",
                "value": 2
              },
              {
                "text": "全额退款",
                "value": 3
              }
            ],
            "evaluate_status_localdata": [
              {
                "text": "未评价",
                "value": 0
              },
              {
                "text": "已评价",
                "value": 1
              }
            ]
          },
          ...enumConverter
        },
        imageStyles: {
          width: 64,
          height: 64
        },
        exportExcel: {
          "filename": "intangible_userorders.xls",
          "type": "xls",
          "fields": {
            "用户ID": "user_id",
            "订单类型": "order_type",
            "订单状态": "order_status",
            "支付状态": "pay_status",
            "收货地址ID": "address_id",
            "订单商品": "order_items",
            "商品tradecode": "order_tradecodes",
            "店铺分组": "shop_groups",
            "商品总金额": "total_amount",
            "运费": "shipping_fee",
            "优惠金额": "discount_amount",
            "实付金额": "final_amount",
            "支付方式": "payment_method",
            "支付时间": "pay_time",
            "发货时间": "ship_time",
            "收货时间": "receive_time",
            "完成时间": "finish_time",
            "取消时间": "cancel_time",
            "取消原因": "cancel_reason",
            "订单备注": "remark",
            "创建时间": "create_time",
            "过期时间": "expire_time",
            "评价状态": "evaluate_status"
          }
        },
        exportExcelData: []
      }
    },
    onLoad() {
      this._filter = {}
    },
    onReady() {
      this.$refs.udb.loadData()
    },
    methods: {
      onqueryload(data) {
        this.exportExcelData = data
      },
      getWhere() {
        const query = this.query.trim()
        if (!query) {
          return ''
        }
        const queryRe = new RegExp(query, 'i')
        return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
      },
      search() {
        const newWhere = this.getWhere()
        this.where = newWhere
        this.$nextTick(() => {
          this.loadData()
        })
      },
      loadData(clear = true) {
        this.$refs.udb.loadData({
          clear
        })
      },
      onPageChanged(e) {
        this.selectedIndexs.length = 0
        this.$refs.table.clearSelection()
        this.$refs.udb.loadData({
          current: e.current
        })
      },
      navigateTo(url, clear) {
        // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
        uni.navigateTo({
          url,
          events: {
            refreshData: () => {
              this.loadData(clear)
            }
          }
        })
      },
      // 多选处理
      selectedItems() {
        var dataList = this.$refs.udb.dataList
        return this.selectedIndexs.map(i => dataList[i]._id)
      },
      // 批量删除
      delTable() {
        this.$refs.udb.remove(this.selectedItems(), {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      // 多选
      selectionChange(e) {
        this.selectedIndexs = e.detail.index
      },
      confirmDelete(id) {
        this.$refs.udb.remove(id, {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      sortChange(e, name) {
        this.orderByFieldName = name;
        if (e.order) {
          this.orderby = name + ' ' + orderByMapping[e.order]
        } else {
          this.orderby = ''
        }
        this.$refs.table.clearSelection()
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      filterChange(e, name) {
        this._filter[name] = {
          type: e.filterType,
          value: e.filter
        }
        let newWhere = filterToWhere(this._filter, db.command)
        if (Object.keys(newWhere).length) {
          this.where = newWhere
        } else {
          this.where = ''
        }
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      }
    }
  }
</script>

<style>
</style>
